package com.gobrs.async.core.threadpool;

import com.alibaba.ttl.threadpool.TtlExecutors;
import com.gobrs.async.core.config.GobrsAsyncProperties;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.ThreadPoolExecutor;

/**
 * 异步线程池工厂
 */
public class GobrsAsyncThreadPoolFactory {

    /**
     * 线程池配置
     */
    private GobrsAsyncProperties gobrsAsyncProperties;

    /**
     * 默认线程池
     */
    private final ExecutorService COMMON_POOL;

    /**
     * 任务执行者线程池
     */
    private ExecutorService threadPoolExecutor;


    public GobrsAsyncThreadPoolFactory(GobrsAsyncProperties gobrsAsyncProperties) {
        this.gobrsAsyncProperties = gobrsAsyncProperties;
        this.COMMON_POOL = TtlExecutors.getTtlExecutorService(createDefaultThreadPool());
        this.threadPoolExecutor = defaultThreadPool();
    }

    public ExecutorService getThreadPoolExecutor() {
        return threadPoolExecutor;
    }

    /**
     * 用户动态设置线程池参数
     */
    public void setThreadPoolExecutor(ExecutorService threadPoolExecutor) {
        this.threadPoolExecutor = TtlExecutors.getTtlExecutorService(threadPoolExecutor);
    }

    private ExecutorService defaultThreadPool() {
        return COMMON_POOL;
    }

    /**
     * 创建默认线程池
     */
    ThreadPoolExecutor createDefaultThreadPool() {
        GobrsAsyncProperties.ThreadPool threadPool = gobrsAsyncProperties.getThreadPool();
        return new ThreadPoolExecutor(threadPool.getCorePoolSize(),
                threadPool.getMaxPoolSize(), threadPool.getKeepAliveTime(), threadPool.getTimeUnit(),
                threadPool.getWorkQueue(), ThreadPoolBuilder.caseReject(threadPool.getRejectedExecutionHandler()));
    }

}
